<template>
  <!-- 词库选择弹窗 -->
  <el-dialog
    title="选择词库"
    :visible.sync="visible"
    width="90%"
    :close-on-click-modal="false"
    top="15%"
    :show-close="false"
    center
    @close="handleClose"
  >
    <!-- 加载动画 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-content">
        <i class="el-icon-loading"></i>
        <p>加载中...</p>
      </div>
    </div>

    <div v-else class="lexicon-select-container">
      <!-- 固定人物信息区域（不随滚动变化） -->
      <div class="user-info-fixed">
        <div class="user-avatar">
          <img :src="selectedUser.avatar" :alt="selectedUser.studentName">
        </div>
        <div class="user-details">
          <h3>{{ selectedUser.name }}</h3>
          <p class="lexicon-count">已开通词库 {{ selectedUser.hasBookNumber }} 个</p>
          <!-- 总体进度 -->
          <div class="overall-progress">
            <div class="progress-header">
              <span>学习总进度</span>
              <span class="progress-percent">{{ selectedUser.overallProgress }}%</span>
            </div>
            <el-progress
              :stroke-width="8"
              :percentage="selectedUser.overallProgress"
              :status="getProgressStatus(selectedUser.overallProgress)"
            />
          </div>
        </div>
      </div>

      <!-- 词库列表区域（可滚动） -->
      <div class="lexicon-list-container">
        <!-- 无词库数据时显示 -->
        <div v-if="!selectedUser.hasBookList || selectedUser.hasBookList.length === 0" class="no-lexicon-data">
          <i class="el-icon-book-open"/>
          <p>暂无已开通词库数据</p>
        </div>

        <!-- 词库列表 -->
        <div v-else class="lexicon-list">
          <div
            v-for="(lexicon, index) in selectedUser.hasBookList"
            :key="index"
            class="lexicon-item"
            :class="{ 'selected-lexicon': selectedLexiconIndex === index }"
            @click="selectLexicon(lexicon, index)"
          >
            <!-- 词库封面 -->
            <div class="lexicon-cover">
              <img :src="lexicon.cover || defaultCover" :alt="lexicon.name">
            </div>

            <!-- 词库信息与进度 -->
            <div class="lexicon-info">
              <h4 class="lexicon-name">{{ lexicon.bookName }}</h4>

              <!-- 数量统计（总数/已学/未学） -->
              <div class="word-count-stats">
                <span class="total">总数: {{ lexicon.wordCount }}</span>
                <span class="learned">已学: {{ lexicon.studiedCount }}</span>
                <span class="unlearned">未学: {{ lexicon.unlearnedCount }}</span>
              </div>

              <!-- 词库进度条 -->
              <div class="lexicon-progress">
                <el-progress
                  :stroke-width="6"
                  :percentage="lexicon.progress"
                  :status="getProgressStatus(lexicon.progress)"
                />
              </div>
            </div>

            <!-- 选中状态图标 -->
            <div v-if="selectedLexiconIndex === index" class="selected-icon">
              <i class="el-icon-check"/>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 弹窗底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" :disabled="confirmLoading">取消</el-button>
      <el-button
        type="primary"
        :disabled="selectedLexiconIndex === -1 || confirmLoading"
        :loading="confirmLoading"
        @click="confirmSelect"
      >
        {{ confirmLoading ? '提交中...' : '确认选择' }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { changeBookPageInfo, setNewBookNowStudy } from '@/api/student'

export default {
  name: 'VocabularyChooseDialog',
  props: {
    // 控制弹窗显示/隐藏（由父组件传入）
    visible: {
      type: Boolean,
      default: false
    },
    studentId: {
      type: String,
      default: ''
    },
    studentNowStudentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      selectedUser: {}, // 当前选中的用户
      selectedLexiconIndex: -1, // 当前选中的词库索引（-1表示未选中）
      selectedLexicon: null, // 当前选中的词库数据
      defaultCover: require('@/assets/bookCover.png'), // 默认词库封面
      loading: false, // 新增：加载状态
      confirmLoading: false, // 新增：确认按钮加载状态
      isSubmitting: false // 新增：防抖标志
    }
  },
  watch: {
    // 监听弹窗显示状态，初始化数据
    visible(newVal) {
      if (newVal) {
        this.initData()
      } else {
        this.resetState()
      }
    },
    // 监听默认用户索引变化，更新选中用户
    defaultUserIndex(newVal) {
      if (this.visible) {
        this.selectedUser = this.userList[newVal] || {}
        this.resetLexiconSelect()
      }
    }
  },
  mounted() {
    if (this.visible) {
      this.initData()
    }
  },
  methods: {
    // 初始化数据
    async initData() {
      this.loading = true
      try {
        this.selectedUser = await changeBookPageInfo({ stuId: this.studentId })
        this.selectedUser.avatar = process.env.VUE_APP_BASE_HOST + this.selectedUser.avatar
        for (let i = 0; i < this.selectedUser.hasBookList.length; i++) {
          const book = this.selectedUser.hasBookList[i]
          if (book.bookId === this.studentNowStudentId) {
            this.selectedLexiconIndex = i
            this.selectedLexicon = book
          }
        }
      } catch (error) {
        console.error('加载词库数据失败:', error)
        this.$message.error('加载词库数据失败，请重试')
      } finally {
        this.loading = false
      }
    },

    getProgressStatus(progress) {
      progress = 1 * progress
      if (progress >= 100) {
        return 'success'   // 完成
      } else if (progress >= 70) {
        return 'warning'   // 警告
      } else if (progress < 0) {
        return 'exception' // 异常（例如数据错误）
      } else {
        return ''          // 默认（进行中）
      }
    },
    // 重置词库选择状态
    resetLexiconSelect() {
      this.selectedLexiconIndex = -1
      this.selectedLexicon = null
    },

    // 重置组件状态
    resetState() {
      this.resetLexiconSelect()
      this.loading = false
      this.confirmLoading = false
      this.isSubmitting = false
    },

    // 选择词库（单选）
    selectLexicon(lexicon, index) {
      this.selectedLexiconIndex = index
      this.selectedLexicon = lexicon
    },

    // 确认选择，向父组件传递数据（添加防抖）
    async confirmSelect() {
      // 防抖处理
      if (this.isSubmitting) {
        return
      }

      if (this.selectedLexicon) {
        this.isSubmitting = true
        this.confirmLoading = true

        try {
          await setNewBookNowStudy({ stuId: this.studentId, bookId: this.selectedLexicon.bookId })
          // 向父组件发送选中的词库数据和用户数据
          this.$emit('select-confirm', {
            user: this.selectedUser,
            lexicon: this.selectedLexicon
          })
          this.visible = false
        } catch (error) {
          console.error('提交选择失败:', error)
          this.$message.error('提交失败，请重试')
        } finally {
          this.isSubmitting = false
          this.confirmLoading = false
        }
      }
    },

    // 弹窗关闭时的回调
    handleClose() {
      this.resetState()
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
/* 加载动画样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.loading-content {
  text-align: center;
  color: #909399;
}

.loading-content i {
  font-size: 40px;
  margin-bottom: 16px;
  color: #409EFF;
  animation: rotating 2s linear infinite;
}

.loading-content p {
  font-size: 14px;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 弹窗容器 */
.lexicon-select-container {
  display: flex;
  flex-direction: column;
  height: 500px; /* 固定弹窗内容高度 */
  overflow: hidden;
}

/* 固定人物信息区域 */
.user-info-fixed {
  display: flex;
  align-items: center;
  padding: 0 1.5rem 1.5rem 1.5rem;
  background-color: #ffffff;
  border-bottom: 1px solid #f5f5f5;
  /* 关键：固定定位，不随滚动变化 */
  position: sticky;
  top: 0;
  z-index: 10;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details {
  margin-left: 20px;
  width: 80%;
}

.user-details h3 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.lexicon-count {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 1rem;
}

/* 总体进度样式 */
.overall-progress {
  width: 100%;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.3rem;
  font-size: 0.9rem;
}

.progress-percent {
  font-weight: 600;
  color: #3498db;
}

/* 词库列表容器（可滚动） */
.lexicon-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  background-color: #fafafa;
}

.lexicon-list-container::-webkit-scrollbar {
  width: 6px;
}

.lexicon-list-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.lexicon-list-container::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 10px;
}

/* 无词库数据样式 */
.no-lexicon-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  text-align: center;
}

.no-lexicon-data i {
  font-size: 3rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

/* 词库列表样式 */
.lexicon-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* 词库项样式 */
.lexicon-item {
  display: flex;
  align-items: center;
  gap: 1.2rem;
  padding: 1rem;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
}

.lexicon-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

/* 选中的词库样式 */
.lexicon-item.selected-lexicon {
  border-left-color: #3498db;
  background-color: rgba(52, 152, 219, 0.05);
}

/* 词库封面 */
.lexicon-cover {
  width: 60px;
  height: 80px;
  flex-shrink: 0;
}

.lexicon-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 词库信息 */
.lexicon-info {
  flex: 1;
  min-width: 0; /* 解决文本溢出问题 */
}

.lexicon-name {
  font-size: 1rem;
  color: #2c3e50;
  margin-bottom: 0.8rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 数量统计样式 */
.word-count-stats {
  display: flex;
  gap: 1.5rem;
  margin-bottom: 0.5rem;
  font-size: 0.85rem;
  color: #666;
}

.word-count-stats .total {
  color: #3498db;
  font-weight: 500;
}

.word-count-stats .learned {
  color: #2ecc71;
  font-weight: 500;
}

.word-count-stats .unlearned {
  color: #e74c3c;
  font-weight: 500;
}

/* 选中状态图标 */
.selected-icon {
  color: #3498db;
  font-size: 1.2rem;
}

::v-deep .el-dialog__body {
  padding: 0 20px 10px 20px;
}

::v-deep .el-dialog__footer {
  padding: 0 20px 10px;
}
</style>
